"""
>>> period()
(None, None)
>>> period(year=2007)
(datetime.date(2007, 1, 1), datetime.date(2008, 1, 1))
>>> period(year=2007, month=12)
(datetime.date(2007, 12, 1), datetime.date(2008, 1, 1))
>>> period(year=2007, month=12, dayofmonth=3)
(datetime.date(2007, 12, 3), datetime.date(2007, 12, 4))

TODO: 
- Tests for weeks
- Make weeks do not span year
"""

import datetime
from dateutil.relativedelta import relativedelta
from dateutil.relativedelta import MO, TU, WE, TH, FR, SA, SU

def period(year=None, month=None, week=None, dayofmonth=None):
    """
    These combinations of parameters are supported:
    A: ()
    B: (year)
    C: (year, month)
    D: (year, month, dayofmonth)
    E: (year, week)
    """
    # A
    db, de = None, None
    if year is not None:
        db = datetime.date(year, 1, 1)
        de = db
        if month is None and week is None:
            # B
            de = db + relativedelta(years = +1)
        elif month is not None:
            if dayofmonth is None:
                # C
                db = db.replace(month = month)
                de = db + relativedelta(months = +1)
            else:
                # D
                db = db.replace(month = month, day = dayofmonth)
                de = db + relativedelta(days = +1)
        elif week is not None:
            # E
            if week > 0:
                db = db + relativedelta(weekday=MO(-1), weeks=week)
            de = db + relativedelta(weekday=MO(-1), weeks=1)

    return (db, de)

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()

